﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Linq;
using System.Security.Cryptography;

namespace ClassLibrary
{
    public class StringHelper
    {
        string _string;
        public StringHelper(string str)
        {
            _string = str;
        }

        public StringHelper(MemoryStream stream)
        {
            if (stream == null || stream.Length == 0)
            {
                _string = null;
            }

            stream.Flush();
            stream.Position = 0;
            StreamReader sr = new StreamReader(stream);
            _string = sr.ReadToEnd();
        }

        public MemoryStream AsMemoryStream
        {
            get
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(_string);
                return new MemoryStream(byteArray);
            }
        }

        public static string ConvertFromMemoryStream(MemoryStream stream)
        {
            if (stream == null || stream.Length == 0)
            {
                return null;
            }

            stream.Flush();
            stream.Position = 0;
            StreamReader sr = new StreamReader(stream);
            return sr.ReadToEnd();
        }

        public static string GetMd5Sum(string _string)
        {

            // First we need to convert the string into bytes, which

            // means using a text encoder.

            Encoder enc = System.Text.Encoding.Unicode.GetEncoder();



            // Create a buffer large enough to hold the string

            byte[] unicodeText = new byte[_string.Length * 2];

            enc.GetBytes(_string.ToCharArray(), 0, _string.Length, unicodeText, 0, true);



            // Now that we have a byte array we can ask the CSP to hash it

            MD5 md5 = new MD5CryptoServiceProvider();

            byte[] result = md5.ComputeHash(unicodeText);



            // Build the final string by converting each byte

            // into hex and appending it to a StringBuilder

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < result.Length; i++)
            {

                sb.Append(result[i].ToString("X2"));

            }



            // And return it

            return sb.ToString();

        }
    }

    public class LinqToXmlHelper
    {
        public static string GetInnerXml(XElement element)
        {
            try
            {
                StringBuilder innerXml = new StringBuilder();
                element.Nodes().ToList().ForEach(node => innerXml.Append(node.ToString()));
                return innerXml.ToString();
            }
            catch { return string.Empty; }
        }
    }
}
